package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;
import com.google.gson.Gson;
import com.iflytek.cloud.thirdparty.V;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.beans.GlobalRoamingBeans;
import com.sam.im.heiqun.uis.beans.QQCityModel;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangguodong on 2017/9/8.
 */

public class GlobalRoamingActivity extends BaseSwipeBackActivity {

    private static final int HANDLER_CLEARN_ANIM = 1000;
    private static final String TAG = "QuanQiuManYouActivity";
    private static final int FLY_DING_WEI = 1001;
    private static final int HANDLER_STOP_FLY = 1002;
    private static final int HANDLER_LOCATION_BACK = 1003;
    private static final int HANDLER_3_RANDOM = 1004;
    private static final int HANDLER_DELAYED_DU = 1005;

    private static final int SDK_PERMISSION_REQUEST = 127;

    @BindView(R.id.img_diqiu)
    ImageView img_diqiu;
    @BindView(R.id.img_go)
    ImageView img_go;
    @BindView(R.id.img_fly)
    ImageView img_fly;
    @BindView(R.id.txt_city)
    TextView txt_city;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.right2)
    ImageView right2;

    private ObjectAnimator translationY;
    private QQCityModel cityData;

    private boolean isQQMYing = false;
    public boolean haveSound = true;
    private SoundPool soundPool;

    private double latStr = 35.057506;
    private double lngStr = 118.330398;
    private double mylongitude = 0;
    private double mylatitude = 0;
    private String addrStr;
    private int randomCount = 0;
    int transferX;
    PGService mPgService;
    GlobalRoamingBeans globalRoamingBeans ;


    public static void start(Activity activity ){
        Intent intent = new Intent(activity, GlobalRoamingActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.near_person);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        mPgService = PGService.getInstance();
        initCityData();
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        soundPool.load(this, R.raw.roam_change, 1);
        soundPool.load(this, R.raw.qqmy_music, 2);
        getPersimmions();

        right.setBackgroundResource(R.drawable.img_fly);
        right.setVisibility(View.VISIBLE);
        right2.setBackgroundResource(R.drawable.img_sound_yes);
        right2.setVisibility(View.VISIBLE);

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_quan_qiu_man_you;
    }

    @Override
    protected void onResume() {
        super.onResume();
        startComeIn();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HANDLER_CLEARN_ANIM://这里跳转列表页面
                    GlobalRoamingUserListActivity.start(GlobalRoamingActivity.this,globalRoamingBeans,mylongitude,mylatitude,lngStr,latStr);
                    break;
                case HANDLER_STOP_FLY :
//                    Object obj = msg.obj;
//                    if (obj != null) {
//                        model = (QQMYModel) obj;
//                    }
//                    if (translationY != null) {
//                        translationY.cancel();
//                    }
//                    transOut();
                    break;
                case HANDLER_LOCATION_BACK:
//                    doGO();
                    break;
                case HANDLER_3_RANDOM:
                    randomCount++;
                    getRandomCity();
                    break;
                case HANDLER_DELAYED_DU:
                    if (haveSound) {
                        soundPool.play(2, 1, 1, 0, 0, 1);
                    }
                    break;
            }
        }
    };

    @OnClick({R.id.img_go, R.id.right,R.id.right2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back :
                scrollToFinishActivity();
                break;
            case R.id.img_go:
                doGO();
                break;
            case R.id.right:
                LocationAllActivity.start(GlobalRoamingActivity.this);
                break;
            case R.id.right2:
                if (haveSound){
                    right2.setBackgroundResource(R.drawable.img_sound_no);
                    haveSound = false;
                    soundPool.stop(1);
                    soundPool.stop(2);
                }else {
                    haveSound = true ;
                    right2.setBackgroundResource(R.drawable.img_sound_yes);
                }
                break;

        }
    }

    private void doGO() {

        isQQMYing = true;

        img_go.setEnabled(false);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.rotate_animation_slow);
        img_diqiu.startAnimation(animation);

        flyFly();
        getRandomCity();
    }


    private void startComeIn() {
        int imgPx = dp2px(50);
        Display defaultDisplay = getWindowManager().getDefaultDisplay();
        int screenWidth = defaultDisplay.getWidth();
        transferX = screenWidth / 2 + imgPx;
        ObjectAnimator translationX = ObjectAnimator.ofFloat(img_fly, "translationX", 0, -transferX);
        translationX.setDuration(700);
        translationX.start();
    }

    private void comeInFast() {
        int imgPx = dp2px(50);
        Display defaultDisplay = getWindowManager().getDefaultDisplay();
        int screenWidth = defaultDisplay.getWidth();
        transferX = screenWidth / 2 + imgPx;
        ObjectAnimator translationX = ObjectAnimator.ofFloat(img_fly, "translationX", 0, -transferX);
        translationX.setDuration(10);
        translationX.start();
    }
    private void transOut() {
//        if (!shouldJump) {
//            imgGo.setEnabled(true);
            cleanAnim();
//            return;
//        }
        ObjectAnimator translationX = ObjectAnimator.ofFloat(img_fly, "translationX", -transferX, -(1000 + transferX));
        translationX.setDuration(700);
        translationX.start();
        handler.sendEmptyMessageDelayed(HANDLER_CLEARN_ANIM, 700);
    }
    public int dp2px(float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, getResources().getDisplayMetrics());
    }

    private void flyFly() {
        translationY = ObjectAnimator.ofFloat(img_fly, "translationY", 0, 25, 0);
        translationY.setDuration(800);
        translationY.setRepeatCount(-1);
        translationY.start();
    }

    private void cleanAnim() {
        img_go.setEnabled(true);
        img_diqiu.clearAnimation();

        soundPool.stop(1);
        if (translationY != null) {
            translationY.cancel();
        }
        isQQMYing = false;
    }

    private void initCityData() {
        try {
            String cityJson = getResources().getString(R.string.qqmy_json).replace(" ", "");
            cityData = new Gson().fromJson(cityJson, QQCityModel.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void getRandomCity() {
        double random = Math.random();
        if (cityData != null) {
            QQCityModel.ArrayBean array = cityData.getArray();
            if (array != null) {
                List<QQCityModel.ArrayBean.DictBean> dict = array.getDict();
                if (dict != null && !dict.isEmpty()) {
                    int size = dict.size();
                    int position = (int) (random * size);
                    if (size > position) {
                        QQCityModel.ArrayBean.DictBean bean = dict.get(position);
                        if (bean != null) {
                            String lat = bean.getString().get(0);
                            String lng = bean.getString().get(1);
                            String city = bean.getString().get(2);

                            if (lat != null && lng != null && city != null) {

                                if (haveSound) {
                                    soundPool.play(1, 1, 1, 0, 0, 1);
                                }

//                                if (shouldRandom) {
//                                    latStr = Double.valueOf(lat);
//                                    lngStr = Double.valueOf(lng);
                                    addrStr = city;
                                txt_city.setVisibility(View.VISIBLE);
                                txt_city.setText(addrStr);
//                                }

                                if (randomCount < 2) {
                                    handler.sendEmptyMessageDelayed(HANDLER_3_RANDOM, 600);
                                } else {
                                    randomCount = 0;
                                    qqmy();
                                }
                            } else {
                                showToast(getString(R.string.get_data_fail));
                                cleanAnim();
                            }
                        }
                    } else {
                        showToast(getResources().getString(R.string.get_data_fail));
                    }
                } else {
                    showToast(getResources().getString(R.string.get_data_fail));
                }
            } else {
                showToast(getResources().getString(R.string.get_data_fail));
            }
        } else {
            showToast(getResources().getString(R.string.get_data_fail));
        }
    }

    /**
     * 请求漫游信息
     */
    private void qqmy() {
        isQQMYing = true;

        mPgService.findNearby(ToolsUtils.getMyUserId(), ""+latStr, ""+lngStr, "", "0").subscribe(new AbsAPICallback<GlobalRoamingBeans>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.get_data_fail));
            }

            @Override
            public void onNext(GlobalRoamingBeans mglobalRoamingBeans) {
                globalRoamingBeans = mglobalRoamingBeans ;
                transOut();
            }
        });
    }

    private AMapLocationClient locationClient;//高德定位类
    private AMapLocationClientOption mLocationOption;
    private void startLocation() {
        if (locationClient == null) {
            //初始化定位
            locationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            locationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation aMapLocation) {
                    //经度
                    mylongitude = aMapLocation.getLongitude();
                    //纬度
                    mylatitude = aMapLocation.getLatitude();



                    /*//地址信息
                address = aMapLocation.getAddress();
                //城市
                city = aMapLocation.getCity();
                //省份
                province = aMapLocation.getProvince();
                //街道
                street = aMapLocation.getStreet();
                //区
                district = aMapLocation.getDistrict();
                //位置语意信息
                description = aMapLocation.getDescription();
                altitude = aMapLocation.getAltitude();
                //街道号
                streetNum = aMapLocation.getStreetNum();
                //楼层信息
                floor = aMapLocation.getFloor();
                //经度
                longitude = aMapLocation.getLongitude();
                //纬度
                latitude = aMapLocation.getLatitude();
                //poiname
                poiName = aMapLocation.getPoiName();*/
                }
            });
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            locationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            locationClient.startLocation();//启动定位
        }

    }


    @TargetApi(23)
    protected void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            // 读写权限
            int pos = 0 ;
            if (addPermission(permissions, Manifest.permission.ACCESS_FINE_LOCATION)) {
                pos ++ ;
            }
            if (addPermission(permissions, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                pos ++ ;
            }
            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }else {
                startLocation();
            }
        }else {
            //不用动态申请权限
            startLocation();
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                //拒绝了也是可以强行提示的，不过如果再也不提示的情况还没处理
                permissionsList.add(permission);
                return false;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case SDK_PERMISSION_REQUEST:
                Map<String, Integer> perms = new HashMap<String, Integer>();
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                try {
                    int isgre = 0 ;
                    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (2 <= isgre){
                        startLocation();
                    }else {
                        Toast.makeText(this, getResources().getString(R.string.no_pawr_nouse), Toast.LENGTH_SHORT)
                                .show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


}
